﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Folks.UI
{
	[Designer(typeof(Folks.UI.Design.FolksContainerControlDesigner))]
	[ToolboxData("<{0}:FolksContainer runat=server></{0}:FolksContainer>")]
	public class FolksContainer : Panel
	{
		#region Constants
		internal const string ResponseSeparator = "|@|";
		internal const string ContainerPrefixBegin = "<!-- folks:";
        internal const string ContainerPrefixEnd = ":start -->";
		internal const string ContainerSufixBegin = "<!-- folks:";
        internal const string ContainerSufixEnd = ":end -->";
		#endregion

		#region Overriden Methods & Properties
		protected override void OnPreRender(EventArgs e)
		{
			FolksManager.EnsureFolksManager(Page);
			EnsureProgress();
			base.OnPreRender(e);
		}

		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			writer.AddAttribute(HtmlTextWriterAttribute.Scope, "folks");
			AddProgressAttributeToRender(writer);
			base.AddAttributesToRender(writer);
		}

		protected override void Render(HtmlTextWriter writer)
		{
			writer.WriteLine(ContainerPrefixBegin + ClientID + ContainerPrefixEnd);
			FolksManager mgr = FolksManager.GetCurrent(Page);
			if(mgr != null && mgr.IsFolksPostBack && mgr.IsFromContainer && this.Equals(mgr.CurrentContainer))
			{
				base.RenderContents(writer);
			}else
				base.Render(writer);

			writer.WriteLine(ContainerSufixBegin + ClientID + ContainerSufixEnd);
		}

		protected override HtmlTextWriterTag TagKey
		{
			get
			{
				return HtmlTextWriterTag.Div;
			}
		}

		public override bool Equals(object obj)
		{
			return (obj is FolksContainer && ((FolksContainer)obj).ID.Equals(ID));
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
		#endregion

		#region Private Methods

		private void AddProgressAttributeToRender(HtmlTextWriter writer)
		{
			if (!string.IsNullOrEmpty(ProgressControlID))
				writer.AddAttribute(HtmlTextWriterAttribute.Rel, GetSpecifiedProgress().ClientID);
		}

		private void EnsureProgress()
		{
			if (!string.IsNullOrEmpty(ProgressControlID))
			{
				if (GetSpecifiedProgress() == null)
					throw new Exception(string.Format("The specified {0} FolksProgress control was not found!", ProgressControlID));
			}
		}

		private FolksProgress GetSpecifiedProgress()
		{
			return (FolksProgress)FolksManager.GetCurrent(Page).FindControl(ProgressControlID);
		}

		#endregion

		#region Public Properties

		[Category("Behavior")]
		[Description("")] //TODO: Create a cool description
		[IDReferenceProperty(typeof(FolksProgress))]
		public string ProgressControlID
		{
			get
			{
				object progressId = ViewState["ProgressControlID"];
				if (progressId != null)
					return progressId as string;
				return string.Empty;
			}
			set { ViewState["ProgressControlID"] = value; }
		}

		#endregion
	}
}
